{% extends "base.html" %}

{% block head %}
<style>
    :root {
        --primary-color: #1976d2;
        --primary-hover: #1565c0;
        --border-color: #e0e0e0;
        --light-gray: #f5f5f5;
        --text-color: #333;
        --shadow-color: rgba(0, 0, 0, 0.1);
    }

    body {
        color: var(--text-color);
        background-color: #f8f9fa;
    }

    .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }

    .card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
        padding: 20px;
        margin-bottom: 20px;
    }

    .card-header {
        margin: -20px -20px 20px;
        padding: 15px 20px;
        background: var(--light-gray);
        border-radius: 8px 8px 0 0;
        border-bottom: 1px solid var(--border-color);
    }

    .card-header h2 {
        margin: 0;
        font-size: 1.5rem;
        color: var(--primary-color);
    }

    /* 表格容器样式优化 */
    .table-wrapper {
        position: relative;
        margin: 20px -20px;
        background: white;
    }

    .table-container {
        width: 100%;
        overflow-x: auto;
        position: relative;
        max-height: 600px;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: var(--primary-color) var(--light-gray);
    }

    /* 自定义滚动条样式 */
    .table-container::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    .table-container::-webkit-scrollbar-track {
        background: var(--light-gray);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb {
        background: var(--primary-color);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb:hover {
        background: var(--primary-hover);
    }

    /* 滑动指示器 */
    .scroll-indicator {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: white;
        padding: 8px;
        border-radius: 4px;
        font-size: 12px;
        opacity: 0;
        transition: opacity 0.3s;
        pointer-events: none;
    }

    .scroll-indicator.visible {
        opacity: 1;
    }

    /* 表格样式优化 */
    .result-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        margin: 0;
        font-size: 12px;
        min-width: 1200px;
    }

    .result-table th {
        background: #e6f7ff;
        color: #0050b3;
        font-weight: normal;
        position: sticky;
        top: 0;
        z-index: 1;
        white-space: normal;
        word-break: break-word;
        min-width: 120px;
        height: auto;
        padding: 8px 6px;
        line-height: 1.4;
    }

    .result-table td {
        border: 1px solid #d9d9d9;
        padding: 6px 4px;
        text-align: left;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 150px;
    }

    .result-table tr:nth-child(even) {
        background: #f5faff;
    }

    .result-table td:hover {
        overflow: visible;
        white-space: normal;
        word-break: break-all;
        position: relative;
        z-index: 2;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    /* 分页控件美化 */
    .pagination-container {
        background: white;
        padding: 15px;
        border-top: 1px solid var(--border-color);
        border-radius: 0 0 8px 8px;
        display: flex;
        justify-content: flex-end;
        margin-top: 12px;
        gap: 8px;
    }

    .pagination {
        display: flex;
        justify-content: center;
        gap: 8px;
    }

    .pagination button {
        padding: 4px 12px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        background: #fff;
        cursor: pointer;
    }

    .pagination button:disabled {
        background: #f5f5f5;
        cursor: not-allowed;
    }

    .pagination button.active {
        background: #1890ff;
        color: white;
        border-color: #1890ff;
    }

    .pagination-ellipsis {
        color: #555;
        padding: 0 8px;
    }

    .btn {
        padding: 8px 16px;
        border-radius: 4px;
        border: none;
        cursor: pointer;
        font-weight: 500;
        transition: background-color 0.2s;
    }

    .btn-primary {
        background-color: var(--primary-color);
        color: white;
    }

    .btn-primary:hover {
        background-color: var(--primary-hover);
    }

    .btn:disabled {
        opacity: 0.65;
        cursor: not-allowed;
    }

    .spinner {
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #1976d2;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        display: none;
        margin-left: 10px;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .status-message {
        margin-top: 20px;
        padding: 15px;
        border-radius: 4px;
        display: none;
    }

    .status-message.error {
        background-color: #ffebee;
        color: #c62828;
        border: 1px solid #ffcdd2;
    }

    .status-message.success {
        background-color: #e8f5e9;
        color: #2e7d32;
        border: 1px solid #c8e6c9;
    }

    .folder-list {
        margin-top: 20px;
        background-color: #f5f5f5;
        border-radius: 4px;
        padding: 15px;
    }

    .folder-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px;
        background: white;
        border-radius: 4px;
        margin-bottom: 8px;
        transition: background-color 0.2s;
    }

    .folder-item:last-child {
        margin-bottom: 0;
    }

    .folder-item:hover {
        background-color: #f8f9fa;
    }

    .folder-item-left {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .folder-name {
        font-weight: 500;
    }

    .folder-status {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 0.9em;
    }

    .folder-status.exists {
        background-color: #e8f5e9;
        color: #2e7d32;
    }

    .folder-status.not-exists {
        background-color: #ffebee;
        color: #c62828;
    }

    .filter-area {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        padding: 20px;
        margin: 20px 0;
    }

    .filter-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid var(--border-color);
    }

    .filter-title {
        font-size: 16px;
        font-weight: 500;
        color: var(--text-color);
        margin: 0;
    }

    .filter-buttons {
        display: flex;
        gap: 10px;
    }

    .filter-content {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .filter-section {
        margin-bottom: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
    }

    .filter-section-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e0e0e0;
    }

    .relatives-section {
        margin-top: 10px;
        margin-bottom: 15px;
        padding: 15px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
        width: 100%;
    }

    .relatives-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 8px;
        margin-bottom: 10px;
        border-bottom: 1px solid #e0e0e0;
    }

    .relatives-section-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
    }

    .relatives-list {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 15px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 4px;
    }

    #relativesList {
        display: flex;
        flex-direction: column;
        gap: 15px;
        width: 100%;
    }

    .relative-item {
        display: flex;
        align-items: center;
        padding: 10px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
        transition: all 0.2s ease;
        min-width: 0; /* 确保flex item可以收缩 */
    }

    .relative-item:hover {
        background: #f8f9fa;
        border-color: var(--primary-color);
    }

    .relative-item input[type="checkbox"] {
        margin-right: 8px;
        min-width: 16px;
        height: 16px;
        cursor: pointer;
    }

    .relative-item label {
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        color: var(--text-color);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        flex: 1;
        min-width: 0; /* 确保文本可以被截断 */
    }

    .filter-label {
        display: block;
        font-size: 14px;
        font-weight: 500;
        color: #666;
        margin-bottom: 10px;
    }

    /* 按钮样式优化 */
    .btn-primary:disabled {
        background-color: #ccc;
        cursor: not-allowed;
    }

    /* 加载动画样式 */
    .loading {
        text-align: center;
        padding: 20px;
        display: none;
    }

    .loading.active {
        display: block;
    }

    .spinner {
        display: none;
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid var(--primary-color);
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-left: 10px;
        vertical-align: middle;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .filter-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e0e0e0;
    }

    .filter-section-buttons {
        display: flex;
        gap: 8px;
    }

    .btn-sm {
        padding: 4px 8px;
        font-size: 12px;
    }

    .table-actions {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        margin-bottom: 15px;
        padding: 10px;
        background: white;
        border-radius: 4px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    .btn-outline-primary {
        background-color: white;
        color: var(--primary-color);
        border: 1px solid var(--primary-color);
    }

    .btn-outline-primary:hover {
        background-color: var(--primary-color);
        color: white;
    }

    /* 添加资产分类相关样式 */
    .asset-type-list {
        display: flex;
        gap: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 4px;
    }

    .asset-type-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
    }

    .asset-type-item input[type="checkbox"] {
        width: 16px;
        height: 16px;
        cursor: pointer;
    }

    .asset-type-item label {
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        color: var(--text-color);
    }

    /* 添加模态框样式 */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
    }

    .modal-content {
        background-color: #fefefe;
        margin: 5% auto;
        padding: 25px;
        border: 1px solid #888;
        width: 80%;
        max-width: 800px;
        border-radius: 8px;
        max-height: 80vh;
        overflow-y: auto;
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ddd;
    }

    .modal-title {
        font-size: 1.2rem;
        font-weight: 500;
        color: var(--text-color);
        margin: 0;
    }

    .close-button {
        color: #aaa;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
    }

    .close-button:hover {
        color: black;
    }

    .modal-footer {
        margin-top: 20px;
        padding-top: 15px;
        border-top: 1px solid #ddd;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    /* 修改亲属选择按钮样式 */
    .relatives-select-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background: white;
        border: 1px solid var(--primary-color);
        color: var(--primary-color);
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s;
    }

    .relatives-select-btn:hover {
        background: var(--primary-color);
        color: white;
    }

    .relatives-select-btn .selected-count {
        background: var(--primary-color);
        color: white;
        padding: 2px 6px;
        border-radius: 10px;
        font-size: 12px;
    }

    .relatives-select-btn:hover .selected-count {
        background: white;
        color: var(--primary-color);
    }

    /* 适配小屏幕 */
    @media (max-width: 1200px) {
        .relatives-list {
            grid-template-columns: repeat(3, 1fr);
        }
    }

    @media (max-width: 768px) {
        .relatives-list {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media (max-width: 480px) {
        .relatives-list {
            grid-template-columns: repeat(1, 1fr);
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="card">
        <div class="card-header">
            <h2>信息资产分析</h2>
        </div>
        <div class="card-body">
            <!-- 操作按钮 -->
            <div class="action-buttons">
                <button type="button" class="btn btn-primary" id="loadDataBtn">
                    加载已有数据
                    <div id="loadingSpinner" class="spinner"></div>
                </button>
                <button type="button" class="btn btn-primary" id="analyzeDataBtn">
                    分析数据
                    <div id="analyzeSpinner" class="spinner"></div>
                </button>
            </div>

            <!-- 状态消息 -->
            <div id="statusMessage" class="status-message"></div>
            
            <!-- 筛选区域 -->
            <div id="filterArea" class="filter-area">
                <div class="filter-header">
                    <h3 class="filter-title">筛选条件</h3>
                </div>
                <div class="filter-content">
                    <!-- 文件夹选择部分 -->
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">选择被审查人：</div>
                            <div class="filter-section-buttons">
                                <button type="button" class="btn btn-sm btn-primary" id="selectAllFoldersBtn">全选</button>
                                <button type="button" class="btn btn-sm btn-primary" id="deselectAllFoldersBtn">取消全选</button>
                            </div>
                        </div>
                        <div id="folderList" class="folder-list"></div>
                    </div>

                    <!-- 亲属选择按钮 -->
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">亲属选择：</div>
                            <button type="button" class="relatives-select-btn" id="relativesSelectBtn">
                                选择亲属
                                <span class="selected-count" id="selectedRelativesCount">0</span>
                            </button>
                        </div>
                    </div>
                    
                    <!-- 资产分类选择部分 -->
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">选择资产分类：</div>
                            <div class="filter-section-buttons">
                                <button type="button" class="btn btn-sm btn-primary" id="selectAllAssetsBtn">全选</button>
                                <button type="button" class="btn btn-sm btn-primary" id="deselectAllAssetsBtn">取消全选</button>
                            </div>
                        </div>
                        <div id="assetTypeList" class="asset-type-list">
                            <div class="asset-type-item">
                                <input type="checkbox" id="asset-type-house" value="房产">
                                <label for="asset-type-house">房产</label>
                            </div>
                            <div class="asset-type-item">
                                <input type="checkbox" id="asset-type-vehicle" value="车辆">
                                <label for="asset-type-vehicle">车辆</label>
                            </div>
                            <div class="asset-type-item">
                                <input type="checkbox" id="asset-type-valuable" value="贵重物品">
                                <label for="asset-type-valuable">贵重物品</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 亲属选择模态框 -->
            <div id="relativesModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">选择亲属</h3>
                        <span class="close-button" id="closeRelativesModal">&times;</span>
                    </div>
                    <div id="relativesList"></div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-primary" id="cancelRelativesSelection">取消</button>
                        <button type="button" class="btn btn-primary" id="confirmRelativesSelection">确定</button>
                    </div>
                </div>
            </div>

            <!-- 表格操作按钮 -->
            <div class="table-actions">
                <button type="button" class="btn btn-primary" id="applyFilterBtn">应用筛选</button>
                <button type="button" class="btn btn-outline-primary" id="cancelFilterBtn">取消筛选</button>
            </div>

            <!-- 加载动画 -->
            <div id="loading" class="loading">
                正在加载数据，请稍候...
            </div>

            <!-- 结果表格 -->
            <div id="resultContainer" class="card" style="display: none;">
                <div class="table-wrapper">
                    <div class="table-container">
                        <div class="scroll-indicator">向右滑动查看更多</div>
                        <table class="result-table">
                            <thead>
                                <tr id="tableHeader"></tr>
                            </thead>
                            <tbody id="tableBody"></tbody>
                        </table>
                    </div>
                    <div class="pagination-container">
                        <div class="pagination" id="pagination"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const loadDataBtn = document.getElementById('loadDataBtn');
        const analyzeDataBtn = document.getElementById('analyzeDataBtn');
        const loadingSpinner = document.getElementById('loadingSpinner');
        const analyzeSpinner = document.getElementById('analyzeSpinner');
        const statusMessage = document.getElementById('statusMessage');
        const filterArea = document.getElementById('filterArea');
        const folderList = document.getElementById('folderList');
        const applyFilterBtn = document.getElementById('applyFilterBtn');
        const selectAllBtn = document.getElementById('selectAllBtn');
        const deselectAllBtn = document.getElementById('deselectAllBtn');

        let currentPage = 1;
        let totalPages = 1;
        let cachedData = null;
        let itemsPerPage = 20;

        // 存储亲属数据的Map
        let relativesMap = new Map();
        // 添加一个持久化的选中状态存储
        let persistentSelectedRelatives = new Set();

        // 添加模态框相关变量
        const relativesModal = document.getElementById('relativesModal');
        const relativesSelectBtn = document.getElementById('relativesSelectBtn');
        const closeRelativesModal = document.getElementById('closeRelativesModal');
        const cancelRelativesSelection = document.getElementById('cancelRelativesSelection');
        const confirmRelativesSelection = document.getElementById('confirmRelativesSelection');
        const selectedRelativesCount = document.getElementById('selectedRelativesCount');

        // 临时存储选中的亲属，用于取消操作
        let tempSelectedRelatives = new Set();

        // 加载数据和文件夹列表
        async function loadFullData() {
            try {
                loadingSpinner.style.display = 'inline-block';
                loadDataBtn.disabled = true;
                filterArea.style.display = 'none';
                document.getElementById('loading').classList.add('active');

                // 获取文件夹列表
                console.log('[DEBUG] 开始获取文件夹列表');
                const foldersResponse = await fetch('/information-assets/check-data');
                const foldersData = await foldersResponse.json();
                console.log('[DEBUG] 获取到的文件夹数据:', foldersData);
                
                // 显示文件夹列表
                if (foldersData.folders && foldersData.folders.length > 0) {
                    folderList.innerHTML = '';
                    relativesMap.clear();
                    
                    console.log('[DEBUG] 开始处理文件夹列表');
                    foldersData.folders.forEach(folder => {
                        console.log('[DEBUG] 处理文件夹:', folder);
                        if (folder.exists) {
                            const folderItem = document.createElement('div');
                            folderItem.className = 'folder-item';
                            
                            const checkbox = document.createElement('input');
                            checkbox.type = 'checkbox';
                            checkbox.id = folder.name;
                            checkbox.value = folder.name;
                            checkbox.addEventListener('change', () => {
                                console.log(`[DEBUG] 文件夹 ${folder.name} 的选中状态改变`);
                                updateRelativesList();
                            });
                            
                            const label = document.createElement('label');
                            label.htmlFor = folder.name;
                            label.textContent = folder.name;
                            
                            folderItem.appendChild(checkbox);
                            folderItem.appendChild(label);
                            folderList.appendChild(folderItem);

                            // 存储亲属数据
                            if (folder.relatives && Array.isArray(folder.relatives)) {
                                console.log(`[DEBUG] 存储文件夹 ${folder.name} 的亲属数据:`, folder.relatives);
                                relativesMap.set(folder.name, folder.relatives);
                            }
                        }
                    });
                    
                    console.log('[DEBUG] relativesMap 内容:', Array.from(relativesMap.entries()));
                    filterArea.style.display = 'block';
                    updateRelativesList();
                }

                // 获取全量数据
                const response = await fetch('/information-assets/get-full-data');
                const result = await response.json();

                if (result.success) {
                    cachedData = result.data;
                    totalPages = Math.ceil(cachedData.length / itemsPerPage);
                    currentPage = 1;
                    displayPageData();
                    statusMessage.textContent = '数据加载成功';
                    statusMessage.className = 'status-message success';
                } else {
                    statusMessage.textContent = result.error || '暂无数据';
                    statusMessage.className = 'status-message error';
                }
                statusMessage.style.display = 'block';
            } catch (error) {
                console.error('[DEBUG] 错误:', error);
                statusMessage.textContent = '加载数据时出错';
                statusMessage.className = 'status-message error';
                statusMessage.style.display = 'block';
            } finally {
                loadingSpinner.style.display = 'none';
                loadDataBtn.disabled = false;
                document.getElementById('loading').classList.remove('active');
            }
        }

        // 分析数据
        async function analyzeData() {
            try {
                analyzeSpinner.style.display = 'inline-block';
                analyzeDataBtn.disabled = true;
                statusMessage.style.display = 'none';

                const response = await fetch('/information-assets/analyze-data', {
                    method: 'POST'
                });
                const result = await response.json();

                if (result.success) {
                    statusMessage.textContent = '数据分析完成，正在重新加载数据...';
                    statusMessage.className = 'status-message success';
                    await loadFullData();
                } else {
                    statusMessage.textContent = result.error || '数据分析失败';
                    statusMessage.className = 'status-message error';
                }
                statusMessage.style.display = 'block';
            } catch (error) {
                console.error('Error:', error);
                statusMessage.textContent = '分析数据时出错';
                statusMessage.className = 'status-message error';
                statusMessage.style.display = 'block';
            } finally {
                analyzeSpinner.style.display = 'none';
                analyzeDataBtn.disabled = false;
            }
        }

        // 打开亲属选择模态框
        relativesSelectBtn.addEventListener('click', () => {
            // 更新亲属列表
            updateRelativesList();
            // 保存当前选中状态到临时存储
            tempSelectedRelatives = new Set(persistentSelectedRelatives);
            // 显示模态框
            relativesModal.style.display = 'block';
        });

        // 修改确认按钮的处理函数
        confirmRelativesSelection.addEventListener('click', () => {
            // 更新持久化的选中状态
            persistentSelectedRelatives = new Set(getSelectedRelatives());
            // 更新选中计数
            selectedRelativesCount.textContent = persistentSelectedRelatives.size;
            relativesModal.style.display = 'none';
        });

        // 修改取消按钮的处理函数
        cancelRelativesSelection.addEventListener('click', () => {
            // 恢复之前的选中状态
            const checkboxes = document.querySelectorAll('#relativesList input[type="checkbox"]');
            checkboxes.forEach(cb => {
                cb.checked = tempSelectedRelatives.has(cb.value);
            });
            relativesModal.style.display = 'none';
        });

        // 点击模态框外部关闭
        window.addEventListener('click', (event) => {
            if (event.target === relativesModal) {
                relativesModal.style.display = 'none';
            }
        });

        // 修改updateRelativesList函数
        function updateRelativesList() {
            const relativesListContainer = document.getElementById('relativesList');
            relativesListContainer.innerHTML = '';
            
            const selectedFolders = getSelectedFolders();
            console.log('[DEBUG] 选中的文件夹:', selectedFolders);

            // 为每个选中的文件夹创建一个亲属区域
            selectedFolders.forEach(folderName => {
                console.log(`[DEBUG] 处理文件夹 ${folderName} 的亲属数据`);
                const relatives = relativesMap.get(folderName) || [];
                console.log(`[DEBUG] 文件夹 ${folderName} 的亲属数据:`, relatives);

                if (relatives.length > 0) {
                    // 创建文件夹的亲属区域
                    const relativesSection = document.createElement('div');
                    relativesSection.className = 'relatives-section';

                    // 创建区域标题和按钮
                    const sectionHeader = document.createElement('div');
                    sectionHeader.className = 'relatives-section-header';

                    const sectionTitle = document.createElement('div');
                    sectionTitle.className = 'relatives-section-title';
                    sectionTitle.textContent = `${folderName} 的亲属`;

                    const buttonGroup = document.createElement('div');
                    buttonGroup.className = 'filter-section-buttons';

                    const selectAllBtn = document.createElement('button');
                    selectAllBtn.type = 'button';
                    selectAllBtn.className = 'btn btn-sm btn-primary';
                    selectAllBtn.textContent = '全选';
                    selectAllBtn.onclick = () => selectAllRelativesInFolder(folderName);

                    const deselectAllBtn = document.createElement('button');
                    deselectAllBtn.type = 'button';
                    deselectAllBtn.className = 'btn btn-sm btn-primary';
                    deselectAllBtn.textContent = '取消全选';
                    deselectAllBtn.onclick = () => deselectAllRelativesInFolder(folderName);

                    buttonGroup.appendChild(selectAllBtn);
                    buttonGroup.appendChild(deselectAllBtn);
                    sectionHeader.appendChild(sectionTitle);
                    sectionHeader.appendChild(buttonGroup);
                    relativesSection.appendChild(sectionHeader);

                    // 创建亲属列表
                    const relativesList = document.createElement('div');
                    relativesList.className = 'relatives-list';
                    relativesList.id = `relatives-${folderName}`;

                    relatives.forEach(([name, relation]) => {
                        if (name && relation) {
                            const relativeItem = document.createElement('div');
                            relativeItem.className = 'relative-item';
                            
                            const checkbox = document.createElement('input');
                            checkbox.type = 'checkbox';
                            checkbox.id = `relative-${folderName}-${name}`;
                            checkbox.value = name;
                            checkbox.dataset.folder = folderName;
                            // 使用持久化的选中状态
                            checkbox.checked = persistentSelectedRelatives.has(name);
                            
                            const label = document.createElement('label');
                            label.htmlFor = `relative-${folderName}-${name}`;
                            label.textContent = `${name}（${relation}）`;
                            
                            relativeItem.appendChild(checkbox);
                            relativeItem.appendChild(label);
                            relativesList.appendChild(relativeItem);
                        }
                    });

                    relativesSection.appendChild(relativesList);
                    relativesListContainer.appendChild(relativesSection);
                }
            });

            // 更新选中计数
            selectedRelativesCount.textContent = persistentSelectedRelatives.size;
        }

        // 全选指定文件夹的亲属
        function selectAllRelativesInFolder(folderName) {
            const checkboxes = document.querySelectorAll(`#relatives-${folderName} input[type="checkbox"]`);
            checkboxes.forEach(cb => {
                cb.checked = true;
            });
        }

        // 取消全选指定文件夹的亲属
        function deselectAllRelativesInFolder(folderName) {
            const checkboxes = document.querySelectorAll(`#relatives-${folderName} input[type="checkbox"]`);
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
        }

        // 全选所有亲属
        function selectAllRelatives() {
            const selectedFolders = getSelectedFolders();
            selectedFolders.forEach(folderName => {
                selectAllRelativesInFolder(folderName);
            });
        }

        // 取消全选所有亲属
        function deselectAllRelatives() {
            const selectedFolders = getSelectedFolders();
            selectedFolders.forEach(folderName => {
                deselectAllRelativesInFolder(folderName);
            });
        }

        // 获取所有选中的亲属
        function getSelectedRelatives() {
            const checkboxes = document.querySelectorAll('#relativesList input[type="checkbox"]:checked');
            return Array.from(checkboxes).map(cb => cb.value);
        }

        // 获取选中的文件夹
        function getSelectedFolders() {
            const checkboxes = folderList.querySelectorAll('input[type="checkbox"]:checked');
            return Array.from(checkboxes).map(cb => cb.value);
        }

        // 全选所有
        function selectAll() {
            selectAllFolders();
            selectAllRelatives();
        }

        // 取消全选所有
        function deselectAll() {
            deselectAllFolders();
            deselectAllRelatives();
        }

        // 全选文件夹
        function selectAllFolders() {
            const checkboxes = folderList.querySelectorAll('input[type="checkbox"]');
            checkboxes.forEach(cb => {
                cb.checked = true;
            });
            updateRelativesList();
        }

        // 取消全选文件夹
        function deselectAllFolders() {
            const checkboxes = folderList.querySelectorAll('input[type="checkbox"]');
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
            updateRelativesList();
        }

        // 获取选中的资产分类
        function getSelectedAssetTypes() {
            const checkboxes = document.querySelectorAll('#assetTypeList input[type="checkbox"]:checked');
            return Array.from(checkboxes).map(cb => cb.value);
        }

        // 全选资产分类
        function selectAllAssetTypes() {
            const checkboxes = document.querySelectorAll('#assetTypeList input[type="checkbox"]');
            checkboxes.forEach(cb => {
                cb.checked = true;
            });
        }

        // 取消全选资产分类
        function deselectAllAssetTypes() {
            const checkboxes = document.querySelectorAll('#assetTypeList input[type="checkbox"]');
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
        }

        // 修改应用筛选函数
        async function applyFilter() {
            const selectedFolders = getSelectedFolders();
            const selectedRelatives = getSelectedRelatives();
            const selectedAssetTypes = getSelectedAssetTypes();
            
            if (selectedFolders.length === 0) {
                alert('请至少选择一个被审查人');
                return;
            }

            try {
                document.getElementById('loading').classList.add('active');
                
                const params = new URLSearchParams();
                selectedFolders.forEach(folder => {
                    params.append('folders', folder);
                });
                selectedRelatives.forEach(relative => {
                    params.append('relatives', relative);
                });
                selectedAssetTypes.forEach(assetType => {
                    params.append('asset_types', assetType);
                });

                const response = await fetch(`/information-assets/get-data?${params.toString()}`);
                const result = await response.json();

                if (result.success) {
                    cachedData = result.data;
                    totalPages = Math.ceil(cachedData.length / itemsPerPage);
                    currentPage = 1;
                    displayPageData();
                } else {
                    alert(result.error || '获取数据失败');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('筛选数据时出错');
            } finally {
                document.getElementById('loading').classList.remove('active');
            }
        }

        // 显示分页数据
        function displayPageData(page = currentPage) {
            if (!cachedData) return;

            const start = (page - 1) * itemsPerPage;
            const end = start + itemsPerPage;
            const pageData = cachedData.slice(start, end);

            const container = document.getElementById('resultContainer');
            const tableHeader = document.getElementById('tableHeader');
            const tableBody = document.getElementById('tableBody');

            // 清空现有内容
            tableHeader.innerHTML = '';
            tableBody.innerHTML = '';

            if (!pageData || pageData.length === 0) {
                container.style.display = 'none';
                return;
            }

            // 计算资产类型总额和资产总额
            const assetTotalsByFolder = new Map(); // 按文件夹和资产类型统计
            const folderTotals = new Map(); // 按文件夹统计总额

            // 先计算所有数据的总额，而不是只计算当前页的数据
            cachedData.forEach(row => {
                const folderKey = row['文件夹'];
                const assetType = row['资产类型'];
                const amount = parseFloat(row['资产金额'] || 0);

                // 按文件夹和资产类型统计
                if (!assetTotalsByFolder.has(folderKey)) {
                    assetTotalsByFolder.set(folderKey, new Map());
                }
                const folderAssets = assetTotalsByFolder.get(folderKey);
                folderAssets.set(assetType, (folderAssets.get(assetType) || 0) + amount);

                // 按文件夹统计总额
                folderTotals.set(folderKey, (folderTotals.get(folderKey) || 0) + amount);
            });

            // 生成表头
            const columns = [...Object.keys(pageData[0]), '资产类型总额', '资产总额'];
            
            // 定义期望的列顺序
            const preferredOrder = ['文件夹', '资产总额', '资产类型', '资产类型总额', '资产信息', '资产金额', '所属人员'];
            
            // 重新排序列
            const orderedColumns = [
                ...preferredOrder.filter(col => columns.includes(col)),
                ...columns.filter(col => !preferredOrder.includes(col))
            ];

            // 生成表头
            orderedColumns.forEach(column => {
                const th = document.createElement('th');
                th.textContent = column;
                tableHeader.appendChild(th);
            });

            // 准备合并单元格的数据
            let lastFolder = null;
            let lastFolderRowspan = 0;
            let lastFolderStartRow = null;
            let lastTotal = null;
            let lastTotalRowspan = 0;
            let lastTotalStartRow = null;

            // 预处理数据，确保资产信息正确显示
            const processedData = [];
            pageData.forEach(row => {
                const assetInfos = row['资产信息'] ? row['资产信息'].split('\n').filter(info => info.trim()) : [];
                if (assetInfos.length > 0) {
                    // 为每条资产信息创建一行
                    assetInfos.forEach((info, index) => {
                        const newRow = {...row};
                        newRow['资产信息'] = info;
                        // 只在第一行显示其他信息
                        if (index > 0) {
                            newRow['资产类型'] = '';
                            newRow['资产类型总额'] = '';
                        }
                        processedData.push(newRow);
                    });
                } else {
                    processedData.push(row);
                }
            });

            // 创建所有行
            const rows = processedData.map((row, index) => {
                const tr = document.createElement('tr');
                const currentFolder = row['文件夹'];
                const currentTotal = folderTotals.get(currentFolder);
                const currentAssetType = row['资产类型'];

                orderedColumns.forEach(column => {
                    // 如果是文件夹列且与上一行相同，跳过创建单元格
                    if (column === '文件夹' && currentFolder === lastFolder) {
                        return;
                    }
                    // 如果是资产总额列，只有当文件夹相同且总额相同时才跳过创建单元格
                    if (column === '资产总额' && currentFolder === lastFolder && currentTotal === lastTotal) {
                        return;
                    }


                    const td = document.createElement('td');
                    
                    if (column === '资产类型总额') {
                        if (row['资产类型']) {  // 只在有资产类型的行显示总额
                            const folderAssets = assetTotalsByFolder.get(row['文件夹']);
                            const assetTypeTotal = folderAssets ? folderAssets.get(row['资产类型']) || 0 : 0;
                            td.style.textAlign = 'right';
                            td.textContent = assetTypeTotal.toLocaleString('zh-CN', {
                                minimumFractionDigits: 2,
                                maximumFractionDigits: 2
                            });
                        }
                    } else if (column === '资产总额') {
                        td.style.textAlign = 'right';
                        td.textContent = currentTotal.toLocaleString('zh-CN', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2
                        });
                    } else if (column === '资产金额') {
                        const value = row[column];
                        td.style.textAlign = 'right';
                        td.textContent = (typeof value === 'number' ? value : 0).toLocaleString('zh-CN', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2
                        });
                    } else {
                        const value = row[column];
                        td.textContent = value || '';
                    }
                    
                    tr.appendChild(td);
                });

                // 更新合并单元格的计数
                if (currentFolder !== lastFolder) {
                    // 处理前一个文件夹的rowspan
                    if (lastFolderStartRow && lastFolderRowspan > 1) {
                        const td = lastFolderStartRow.children[orderedColumns.indexOf('文件夹')];
                        if (td) td.rowSpan = lastFolderRowspan;
                    }
                    // 处理前一个总额的rowspan
                    if (lastTotalStartRow && lastTotalRowspan > 1) {
                        const td = lastTotalStartRow.children[orderedColumns.indexOf('资产总额')];
                        if (td) td.rowSpan = lastTotalRowspan;
                    }
                    // 重置计数
                    lastFolder = currentFolder;
                    lastFolderRowspan = 1;
                    lastFolderStartRow = tr;
                    lastTotal = currentTotal;
                    lastTotalRowspan = 1;
                    lastTotalStartRow = tr;
                } else {
                    // 文件夹相同时
                    lastFolderRowspan++;
                    if (currentTotal === lastTotal) {
                        lastTotalRowspan++;
                    } else {
                        if (lastTotalStartRow && lastTotalRowspan > 1) {
                            const td = lastTotalStartRow.children[orderedColumns.indexOf('资产总额')];
                            if (td) td.rowSpan = lastTotalRowspan;
                        }
                        lastTotal = currentTotal;
                        lastTotalRowspan = 1;
                        lastTotalStartRow = tr;
                    }
                }

                return tr;
            });

            // 处理最后一组的rowspan
            if (lastFolderStartRow && lastFolderRowspan > 1) {
                const td = lastFolderStartRow.children[orderedColumns.indexOf('文件夹')];
                if (td) td.rowSpan = lastFolderRowspan;
            }
            if (lastTotalStartRow && lastTotalRowspan > 1) {
                const td = lastTotalStartRow.children[orderedColumns.indexOf('资产总额')];
                if (td) td.rowSpan = lastTotalRowspan;
            }

            // 将所有行添加到表格
            rows.forEach(tr => tableBody.appendChild(tr));

            // 更新分页
            updatePagination();
            container.style.display = 'block';
        }

        // 更新分页控件
        function updatePagination() {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';

            if (totalPages <= 1) return;

            // 上一页
            const prevButton = document.createElement('button');
            prevButton.textContent = '上一页';
            prevButton.disabled = currentPage === 1;
            prevButton.onclick = () => {
                if (currentPage > 1) {
                    currentPage--;
                    displayPageData();
                }
            };
            pagination.appendChild(prevButton);

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (
                    i === 1 || // 第一页
                    i === totalPages || // 最后一页
                    (i >= currentPage - 2 && i <= currentPage + 2) // 当前页附近
                ) {
                    const pageButton = document.createElement('button');
                    pageButton.textContent = i;
                    pageButton.classList.toggle('active', i === currentPage);
                    pageButton.onclick = () => {
                        currentPage = i;
                        displayPageData();
                    };
                    pagination.appendChild(pageButton);
                } else if (
                    i === currentPage - 3 || // 当前页前的省略号
                    i === currentPage + 3 // 当前页后的省略号
                ) {
                    const ellipsis = document.createElement('span');
                    ellipsis.textContent = '...';
                    ellipsis.className = 'pagination-ellipsis';
                    pagination.appendChild(ellipsis);
                }
            }

            // 下一页
            const nextButton = document.createElement('button');
            nextButton.textContent = '下一页';
            nextButton.disabled = currentPage === totalPages;
            nextButton.onclick = () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    displayPageData();
                }
            };
            pagination.appendChild(nextButton);
        }

        // 修改取消筛选函数
        function cancelFilter() {
            // 清除所有选中状态
            const allCheckboxes = document.querySelectorAll('input[type="checkbox"]');
            allCheckboxes.forEach(cb => {
                cb.checked = false;
            });
            
            // 清除持久化的选中状态
            persistentSelectedRelatives.clear();
            
            // 更新亲属列表
            updateRelativesList();
            
            // 重新加载全量数据
            loadFullData();
        }

        // 绑定按钮事件
        loadDataBtn.addEventListener('click', loadFullData);
        analyzeDataBtn.addEventListener('click', analyzeData);
        applyFilterBtn.addEventListener('click', applyFilter);
        document.getElementById('cancelFilterBtn').addEventListener('click', cancelFilter);
        
        // 绑定文件夹全选按钮事件
        document.getElementById('selectAllFoldersBtn').addEventListener('click', selectAllFolders);
        document.getElementById('deselectAllFoldersBtn').addEventListener('click', deselectAllFolders);
        
        // 绑定资产分类全选按钮事件
        document.getElementById('selectAllAssetsBtn').addEventListener('click', selectAllAssetTypes);
        document.getElementById('deselectAllAssetsBtn').addEventListener('click', deselectAllAssetTypes);

        // 初始加载数据
        loadFullData();
    });
</script>
{% endblock %}